package org.example.weather.bigscreen.portal.task;


import lombok.extern.slf4j.Slf4j;
import org.example.weather.bigscreen.core.api.dto.AreaDTO;
import org.example.weather.bigscreen.core.api.dto.BaiduWeatherDTO;
import org.example.weather.bigscreen.core.api.dto.WeatherInfoDTO;
import org.example.weather.bigscreen.portal.client.BaiduWeatherClient;
import org.example.weather.bigscreen.portal.client.CoreAreaClient;
import org.example.weather.bigscreen.portal.client.CoreWeatherClient;
import org.example.weather.bigscreen.portal.client.WeatherAreaClient;
import org.example.weather.bigscreen.portal.dto.*;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.OffsetDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * Created on 2022-07-22.
 *
 * @author chenyu
 */
@Component
@Slf4j
public class WeatherTask {
    private BaiduWeatherClient baiduWeatherClient;
    private CoreAreaClient coreAreaClient;
    private CoreWeatherClient coreWeatherClient;
    private  RedissonClient redissonClient;
    private WeatherAreaClient weatherAreaClient;
    @Value("${api.baidu.weather.dataType:all}")
    private String dataType;
    @Value("${api.baidu.weather.ak:m4rcfGdiZUvq4ug8MiYlnPFS7oV2vtng}")
    private String ak;


    public WeatherTask(BaiduWeatherClient baiduWeatherClient, CoreAreaClient coreAreaClient, CoreWeatherClient coreWeatherClient,RedissonClient redissonClient,WeatherAreaClient weatherAreaClient) {
        this.baiduWeatherClient = baiduWeatherClient;
        this.coreAreaClient = coreAreaClient;
        this.coreWeatherClient = coreWeatherClient;
        this.redissonClient = redissonClient;
        this.weatherAreaClient = weatherAreaClient;
    }






    //@Scheduled(cron = "${baidu.weather.fetch.cron: 0/10 * * * * *}")
    @Scheduled(cron = "${baidu.weather.fetch.cron: 0/10 * * * * ?}")
    public void fetch() throws InterruptedException {
        RLock lock = redissonClient.getLock("my-lock");
        if (lock.tryLock(3, TimeUnit.SECONDS)){
            try {
                System.out.println(OffsetDateTime.now() + " &redisson上锁：" + Thread.currentThread().getId());
                List<AreaDTO> areaDTOS = weatherAreaClient.selectAll(true);
                List<BaiduWeatherDTO> batch = new ArrayList<>();
                Date date = new Date();
                for (int i = 0; i < areaDTOS.size(); i++) {
                    AreaDTO areaDTO = areaDTOS.get(i);
                    BaiduWeatherResultDTO baiduWeatherResultDTO = baiduWeatherClient.fetchWeather(areaDTO.getAreaId(), dataType, ak).getResult();
                    if(baiduWeatherResultDTO!=null){
                        BaiduWeatherNowDTO weathers = baiduWeatherResultDTO.getNow();
                        BaiduWeatherLocationDTO location = baiduWeatherResultDTO.getLocation();
                        List<BaiduWeatherForecastsDTO> forecasts = baiduWeatherResultDTO.getForecasts();
                        BaiduWeatherDTO baiduWeatherDTO = new BaiduWeatherDTO();
                        baiduWeatherDTO.setAreaId(location.getId());
                        baiduWeatherDTO.setAreaLevel(coreAreaClient.selectById(location.getId()).getAreaLevel());
                        baiduWeatherDTO.setWeatherText(weathers.getText());
                        baiduWeatherDTO.setFeelsLike(new BigDecimal(weathers.getFeelsLike()));
                        baiduWeatherDTO.setRh(new BigDecimal(weathers.getRh()));
                        baiduWeatherDTO.setTemp(new BigDecimal(weathers.getTemp()));
                        baiduWeatherDTO.setWindClass(weathers.getWindClass());
                        baiduWeatherDTO.setWindDir(weathers.getWindDir());
                        baiduWeatherDTO.setUploadTime(date);
                        baiduWeatherDTO.setUploadDate(date);
                        baiduWeatherDTO.setTempHigh(new BigDecimal(forecasts.get(0).getHigh()));
                        baiduWeatherDTO.setTempLow(new BigDecimal(forecasts.get(0).getLow()));

                        batch.add(baiduWeatherDTO);
                    }
                    if (batch.size() % 100 == 0 || i == areaDTOS.size() - 1) {
                        coreWeatherClient.upload(batch);
                        batch.clear();

                    }
                    log.info("百度天气采集{}", new Date());
                }

            }catch (Exception e) {
                e.printStackTrace();
            } finally {
                System.out.println(OffsetDateTime.now() + " &redisson解锁：" + Thread.currentThread().getId());

                //释放
                if(lock != null && lock.isLocked() && lock.isHeldByCurrentThread()){
                    lock.unlock();
                }
            }
        }



    }





}

